<?php defined('SYSPATH') or die('No direct script access.');

class Model_Shop extends Model_Filter
{  
    protected $_reload_on_wakeup = false;    
    
    public function get_shops($category = null, $brand = null, $color = null, $composition = null, $season = null, $shop = null, $price = null, $use_denormalization = true, $disable_cache = false)
    {
        $stat = array();
        
        $ids = array();
        $category_id = self::_get_category_id($category, $ids);
        
        $brand_id    = self::_get_brand_id($brand);
        
        $color_id    = self::_get_color_id($color);
        
        $composition_id = self::_get_composition_id($composition);
        
        $season_id   = self::_get_season_id($season);
        
        $shop_id     = self::_get_shop_id($shop);
        
        $from_price  = self::_get_from_price($price);
        $to_price    = self::_get_to_price($price);
        
        if (!$disable_cache && $shops = Cache::instance()->get('catalog_shops_'.$category_id.'_'.$brand_id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$from_price.'_'.$to_price)) {
            return $shops;
        }
        
        $isset_denormalized_data = null;
        if ($use_denormalization) {
            // Узнаем, используется ли денормализация
            $isset_denormalized_data = self::_isset_denormalized_data($category_id, $brand_id, $color_id, $composition_id, $season_id, $shop_id, $price);   
        }
         
        $tmp_stat = DB::select('shop_id', array(DB::expr('COUNT( * )'), 'count'))
                ->from('products')
                ->where('is_available', '=', 1);
                    
        if (is_array($ids) && count($ids) > 0) {
            $tmp_stat->where('category_id', 'IN', $ids);
        }
                    
        if ($brand_id) {
            $tmp_stat->where('brand_id', '=', $brand_id); 
        }
                    
        if ($color_id) {
            $tmp_stat->where('color_id', '=', $color_id);    
        }
        
        if ($composition_id) {
            $tmp_stat->where('composition_id', '=', $composition_id);   
        }
        
        if ($season_id) {
            $tmp_stat->where('season_id', '=', $season_id);   
        }
        
        if ($from_price) {
            $tmp_stat->where('price', '>=', $from_price);    
        }
        if ($to_price) {
            $tmp_stat->where('price', '<=', $to_price); 
        }
        
        if ($use_denormalization && $isset_denormalized_data) {
            $tmp_stat = self::_get_denormalized_data('shop_id', $category_id, $brand_id, $color_id, $composition_id, $season_id, null, $price);    
        } else {            
            $tmp_stat = $tmp_stat
                    ->group_by('shop_id')
                    ->order_by('count', 'DESC')
                    ->execute()
                    ->as_array();
        }
        
        $ids = array();
        foreach ($tmp_stat as $item) {
            $ids[] = $item['shop_id'];
            $stat[$item['shop_id']] = $item['count'];    
        }
        if (!count($ids)) {
            return array();    
        }
        $shops = array();
        $tmp_shops = ORM::factory('shop')
                        ->where('id', 'IN', $ids)
                        ->find_all()
                        ->as_array();
        foreach ($tmp_shops as $shop) {
            $shop = $shop->as_array(); 
            $shops[$shop['id']] = $shop;
            $shops[$shop['id']]['count'] = $stat[$shop['id']];            
        } 
        usort($shops, array(__CLASS__, '_compare'));    
        
        Cache::instance()->set('catalog_shops_'.$category_id.'_'.$brand_id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$from_price.'_'.$to_price, $shops);
        return $shops;                                
    }
    
    public function get_shops_by_coupons($coupons)
    {
        $shops = array();
        $ids   = array();
        foreach ($coupons as $coupon) {
            $ids[$coupon->shop_id] = $coupon->shop_id;    
        }
        
        $shops = array();
        $tmp_shops = ORM::factory('shop')
                        ->where('id', 'IN', $ids)
                        ->find_all()
                        ->as_array();
        foreach ($tmp_shops as $shop) {
            $shops[$shop->id] = $shop;           
        } 
        
        return $shops;                                         
    }
    
    public function get_shops_by_products($products)
    {
        if (!count($products)) {
            return null;
        }
        $ids  = array();
        foreach ($products as $product) {
            $ids[$product->shop_id] = $product->shop_id;    
        }
        
        $tmp_shops = ORM::factory('shop')
                        ->where('id', 'IN', $ids)
                        ->find_all();
                        
        $shops = array();
        foreach ($tmp_shops as $shop) {
            $shops[$shop->id] = $shop;    
        }
        return $shops;
    }
    
    public function get_shops_by_clicks($clicks)
    {
        return $this->get_shops_by_products($clicks);
    }
    
    public function get_shop_by_url($url)
    {
        return ORM::factory('shop')->where('url', '=', $url)->find();    
    }
    
    public function get_shop_by_partner_and_source_id($partner, $source_id)
    {
        return ORM::factory('shop')
            ->where('partner', '=', $partner)
            ->where('source_id', '=', $source_id)
            ->find();   
    }
    
    public function get_top_shops()
    {
        if ($shops = Cache::instance()->get('top_shops')) {
            return $shops;
        }
        
        $date = new DateTime();        
        $shops = DB::select('*', array(DB::expr('(SELECT COUNT(*) FROM coupons WHERE shop_id = shops.id AND end_date > \''.$date->format('Y-m-d H:i:s').'\')'), 'count'))
                    ->from('shops')
                    ->order_by('count', 'DESC')
                    //->limit(30)
                    ->execute()
                    ->as_array();
        Cache::instance()->set('top_shops', $shops);             
        return $shops;   
    }
    
    public function get_top_shops_with_cashback()
    {
        if ($shops = Cache::instance()->get('top_shops_with_cashback')) {
            return $shops;
        }
        
        $ids = array(6115, 2034, 10723, 5651, 3629, 1001, 2775, 1041, 6454, 10724, 4580, 1780, 1928, 1667, 4486, 3444, 987, 1317, 4581, 2025,);
        
        $shops = ORM::factory('shop')
                    ->where('id', 'IN', $ids)
                    ->find_all();
                    
        Cache::instance()->set('top_shops_with_cashback', $shops);             
        return $shops; 
    }
    
    public function get_recommend_available_shops()
    {
        return ORM::factory('shop')
                    ->where('recommend_payment_size', 'IS NOT', NULL)
                    ->order_by('name', 'ASC')
                    ->find_all();
    }
    
    public function get_all_shops()
    {        
        if ($shops = Cache::instance()->get('all_shops')) {
            //return $shops;
        }
         
        $shops = ORM::factory('shop')
                    ->where('gotolink', '!=', '')
                    ->order_by('name', 'ASC')        
                    ->find_all()
                    ->as_array(); 
                     
        Cache::instance()->set('all_shops', $shops); 
        return $shops;
    }
    
    public function get_logo()
    {
        $image = $this->logo;
        if ($this->image) {
            $image = '/media/uploads/shops/logo-'.$this->url.'.jpg';
        }
        return $image;
    }
    
    public function get_url()
    {
        $url   = $this->gotolink;
        $subid = Model_Main::get_subid(null, null, $this);
        if (strstr($this->gotolink, 'actionpay.ru') !== false) {
            $url = str_replace('/subaccount/', '/'.$subid.'/', $url);
        }
        if (strstr($this->gotolink, 'admitad.com') !== false) {        
            //return str_replace('/?ulp=', '/subid/'.$subid.'/?ulp=', $this->url);
            if (strstr($this->gotolink, 'subaccount') !== false) {
                $url = str_replace('subaccount', $subid, $url);
            } else {
                $url = $this->gotolink.'?subid='.$subid;
            }
        }
        if (strstr($this->gotolink, 'cpl1.ru') !== false) {
            $url = str_replace('/subaccount', '/'.$subid, $url);
        }  
        return $url;      
    }
}
